package com.ls.hnks.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.ls.hnks.util.Result;
import com.ls.hnks.util.ResultCodeEnum;
import com.ls.hnks.model.User;
import com.ls.hnks.service.UserService;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

@Slf4j
@SaCheckLogin
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @SaCheckRole("admin")
    @RequestMapping("/list")
    public Result list(@ApiParam("分页查询的页码数") @RequestParam(value = "page",defaultValue = "1")Integer page,
                       @ApiParam("分页查询的页大小") @RequestParam(value = "size",defaultValue = "20")Integer size){
        return userService.getUserByPage(page,size);
    }

    @RequestMapping("/getSelfInfo")
    public Result getSelfInfo(){
        String userId = StpUtil.getLoginId().toString();
        return userService.getSelfInfo(userId);
    }

    @RequestMapping("/getGroupMember")
    public Result getGroupMember(){
        String userId = StpUtil.getLoginId().toString();
        return userService.getGroupMember(userId);
    }

    @SaCheckRole("admin")
    @RequestMapping("/details/{id}")
    public Result getDetails(@PathVariable String id){
        return userService.getDetails(id);
    }

    @SaCheckRole("admin")
    @PostMapping("/save")
    public Result save(@RequestBody User user){
        log.info("用户信息 --- {}", JSON.toJSONString(user));
        userService.saveUser(user);
        return Result.ok();
    }

    @PostMapping("/updateSelfPwd")
    public Result updateSelfPwd(String oldPassword, String newPassword){
        if(Objects.equals(oldPassword, newPassword)){
            return Result.fail().message("新旧密码一致，无需修改!");
        }

        String selfId = StpUtil.getLoginId().toString();
        User self = userService.getById(selfId);
        if (self == null) {
            return Result.error(ResultCodeEnum.USER_NOT_FOUND);
        }

        String sha1OldPassword = SaSecureUtil.sha1(oldPassword);
        if(!self.getPassword().equals(sha1OldPassword)){
            return Result.fail().message("旧密码错误!");
        }
        String sha1NewPassword = SaSecureUtil.sha1(newPassword);
        self.setPassword(sha1NewPassword);
        userService.updateById(self);
        StpUtil.logout();
        return Result.ok();
    }

    @SaCheckRole("admin")
    @PostMapping("/remove/{id}")
    public Result remove( @PathVariable String id){
        if(userService.getById(id) == null) return Result.error(ResultCodeEnum.USER_NOT_FOUND);
        userService.removeUser(id);
        return Result.ok();
    }


}
